<script setup lang="ts">
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import type { LoginResult } from '@/types/userInfo'
import { getService, checkEnvironment } from '@/utils/oauth'
import { useUserInfoStore } from '@/stores'
import { postLoginMobileAPI } from '@/api/login'
import { getUserTag } from '@/api/user'
import { sendCodeApi } from '@/api/common'

// 短信倒计时
const countDown = ref(0)
let loading = ref(false)
// 获取 code 登录凭证
let code = ''
console.log(code)
const form = ref({
  mobile: '15038301671',
  code: '',
})
const loginSuccess = async (profile: LoginResult) => {
  // 保存会员信息
  const UserInfoStore = useUserInfoStore()
  UserInfoStore.setProfile(profile)
  // 成功提示
  uni.showToast({ icon: 'success', title: '登录成功' })
  const result = await getUserTag()
  if (result.code) {
    if (result.data.length > 0) {
      uni.redirectTo({
        url: '/pages/profile/profile',
      })
    } else {
      uni.redirectTo({
        url: '/pages/welcome/welcome',
      })
    }
  }
}

const checkUserIsLogined = async () => {
  const UserInfoStore = useUserInfoStore()
  const profile = UserInfoStore.$state.profile
  if (profile && profile.id) {
    loginSuccess(profile)
  }
}

onLoad(async () => {
  // #ifdef MP-WEIXIN
  const res = await wx.login()
  code = res.code
  // #endif
  // #ifdef APP-PLUS
  await getService()
  await checkEnvironment(1)
  // #endif
  await checkUserIsLogined()
})
// #ifdef MP-WEIXIN
// 获取用户手机号码
const onGetphonenumber: UniHelper.ButtonOnGetphonenumber = async (ev) => {
  // const { encryptedData, iv } = ev.detail
  console.log(ev)
  // loginSuccess({
  //   id: 1,
  //   username: '13123456789',
  //   nickname: '测试用户',
  //   avatar: '/static/default-avatar.png',
  //   accessToken: '123',
  //   refreshToken: '123',
  //   expires: '123',
  // })

  const res = await postLoginMobileAPI(form.value)
  loginSuccess(res.data)
}
// #endif
// 表单提交
const onSubmit = async () => {
  if (form.value.code == '') {
    uni.showToast({
      title: '请输入验证码',
      icon: 'error',
    })
    return
  }
  const res = await postLoginMobileAPI(form.value)
  if (res.code) {
    loginSuccess(res.data)
  } else {
    uni.showToast({
      title: res.msg,
      icon: 'error',
    })
  }
}

// 发送验证码
async function sendCode() {
  if (countDown.value > 0) return
  if (!form.value.mobile) {
    uni.showToast({
      title: '请输入手机号',
      icon: 'error',
    })
    return
  }
  loading.value = true
  const result = await sendCodeApi({
    mobile: form.value.mobile,
    event: 'login',
  })
  if (result.code) {
    countDown.value = 60
    const timer = setInterval(() => {
      countDown.value--
      if (countDown.value === 0) {
        clearInterval(timer)
      }
    }, 1000)
  }
  if (result.msg) {
    uni.showToast({
      title: result.msg,
      icon: 'error',
    })
  }
  loading.value = false
}
</script>
<template>
  <view class="viewport">
    <view class="logo">
      <image src="/static/logo_icon.png"></image>
    </view>
    <view class="login">
      <!-- 网页端表单登录 -->
      <!-- #ifndef MP-WEIXIN -->
      <uv-form>
        <input
          v-model="form.mobile"
          class="input"
          type="text"
          placeholder="请输入用户名/手机号码"
        />
        <uv-form-item prop="code">
          <uv-input v-model="form.code" placeholder="请输入验证码" clearable></uv-input>
          <!-- 发送验证码 -->
          <uv-button
            class="send_code"
            size="small"
            color="#28bb9c "
            :disabled="countDown > 0"
            @click="sendCode"
            >{{ countDown > 0 ? `${countDown}s` : '发送验证码' }}</uv-button
          >
        </uv-form-item>
        <button @tap="onSubmit" class="button phone">登录</button>
      </uv-form>
      <!-- #endif -->

      <!-- 小程序端授权登录 -->
      <!-- #ifdef MP-WEIXIN -->
      <button class="button phone" open-type="getPhoneNumber" @getphonenumber="onGetphonenumber">
        <text class="icon icon-phone"></text>
        手机号快捷登录
      </button>
      <!-- #endif -->

      <!-- 第三方登录 -->
      <!-- #ifdef APP-PLUS -->
      <view class="extra">
        <view class="caption">
          <text>第三方快捷登录</text>
        </view>
        <view class="options">
          <uv-row class="login_view" justify="space-between">
            <uv-col span="4" class="thirdLogin_btn">
              <uv-image
                width="50px"
                height="50px"
                src="/static/icon/login.png"
                shape="circle"
                @tap="checkEnvironment(1)"
              ></uv-image>
            </uv-col>
          </uv-row>
        </view>
      </view>
      <!-- #endif -->
      <view class="tips">登录/注册即视为你同意《服务条款》和《xxx儿隐私协议》</view>
    </view>
  </view>
</template>

<style scoped lang="scss">
page {
  height: 100%;
}

.viewport {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20rpx 40rpx;
}

.logo {
  flex: 1;
  text-align: center;
  image {
    width: 220rpx;
    height: 220rpx;
    margin-top: 13vh;
  }
}

.login {
  display: flex;
  flex-direction: column;
  height: 60vh;
  padding: 40rpx 20rpx 20rpx;
  .send_code {
    height: 100%;
    padding-left: 20rpx;
    letter-spacing: 1px;
  }
  .input {
    width: 100%;
    height: 80rpx;
    font-size: 28rpx;
    border-radius: 72rpx;
    border: 1px solid #ddd;
    padding-left: 30rpx;
    margin-bottom: 20rpx;
  }

  .button {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 80rpx;
    font-size: 28rpx;
    border-radius: 72rpx;
    color: #fff;
    .icon {
      font-size: 40rpx;
      margin-right: 6rpx;
    }
  }

  .phone {
    background-color: #28bb9c;
  }

  .wechat {
    background-color: #06c05f;
  }

  .extra {
    flex: 1;
    padding: 70rpx 70rpx 0;
    .caption {
      width: 440rpx;
      line-height: 1;
      border-top: 1rpx solid #ddd;
      font-size: 26rpx;
      color: #999;
      position: relative;
      text {
        transform: translate(-40%);
        background-color: #fff;
        position: absolute;
        top: -12rpx;
        left: 50%;
      }
    }

    .options {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-top: 70rpx;
      button {
        padding: 0;
        background-color: transparent;
        &::after {
          border: none;
        }
      }

      .thirdLogin_btn {
        margin: 0px 5rpx;
      }
    }

    .icon {
      font-size: 24rpx;
      color: #444;
      display: flex;
      flex-direction: column;
      align-items: center;

      &::before {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 80rpx;
        height: 80rpx;
        margin-bottom: 6rpx;
        font-size: 40rpx;
        border: 1rpx solid #444;
        border-radius: 50%;
      }
    }
    .icon-weixin::before {
      border-color: #06c05f;
      color: #06c05f;
    }
  }
}

.tips {
  position: absolute;
  bottom: 80rpx;
  left: 20rpx;
  right: 20rpx;
  font-size: 22rpx;
  color: #999;
  text-align: center;
}
</style>
